package com.ssyt.yt1.day28;

/**
 * 【*】有一个共享变量为10，设计4个线程，其中2个线程对其+1，2个线程对其-1
 *
 * @author Hsu.
 * @since 2016年1月4日
 */
class Variable {

	// 共享变量一定要私有并同步
	private int var = 10;

	public synchronized void increment() {
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("increment(), var:" + var++);
	}

	public synchronized void reduce() {
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("reduce(), var:" + var--);
	}

	public void print() {
		System.out.println("print(), var:" + var);
	}
}

public class DataShareDemo {

	public static void main(String[] args) {
		Variable variable = new Variable();
		Thread incrementThread = null;
		Thread reduceThread = null;
		for (int i = 0; i < 2; i++) {
			incrementThread = new Thread() {

				@Override
				public void run() {
					variable.increment();
				}

			};
			incrementThread.start();

			reduceThread = new Thread() {

				@Override
				public void run() {
					variable.reduce();
				}

			};
			reduceThread.start();
		}

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		if (!incrementThread.isAlive() && !reduceThread.isAlive()) {
			variable.print();
		}
	}
}
